#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QSettings>
#include <QMessageBox>

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{

    ui->setupUi(this);
    lus_tcp = aes_tcp_lib::create_aes_tcp();
    lus_tcp->lus_set_order(LITTLE);

    setWindowIcon(QIcon(":/log_l.ico"));

    ui->tableWidget->setEditTriggers(QAbstractItemView::NoEditTriggers);
    lus_tcp->aes_tcp_init();

    connect(lus_tcp, SIGNAL(read_msg(QByteArray)), this, SLOT(do_msg(QByteArray)));

    connect(timer, SIGNAL(timeout()), this, SLOT(public_timer_fun()));
    timer->start(10000);

    connect(lus_tcp, SIGNAL(aes_tcp_connected(void)), this, SLOT(connect_flush(void)));

    //读取配置文件
    QFileInfo f_info("mirror_set.ini");

    if(!f_info.isFile()){

        QMessageBox::information(this, "提示", "初次运行，请先进行必要设置", QMessageBox::Ok);
        mirror_set_window->exec();
    }

    load_set();


    ui->tableWidget->setColumnWidth(0, ui->tableWidget->width());


    mSysTrayIcon = NULL;
}

MainWindow::~MainWindow()
{
    delete ui;
}


void MainWindow::connect_flush()
{
    flush_mirror_faaddr();
    flush_todo();
}

void MainWindow::flush_todo(void)
{

    QString cmd = "<lus_user_msg type=\"mirror_msg\" body=\"requst_list\"  flag=\"todo_list\"/>";
    lus_tcp->sendMessage(cmd.toLatin1() , ENCRYPT_YES);
}

void MainWindow::flush_mirror_faaddr()
{

    QByteArray addr_bc = "<lus_user_msg type=\"from_addr\" body=\"@@\" />";
    QString fix_id = lus_tcp->lus_get_fix_id();
    addr_bc.replace("@@", fix_id.toLatin1());
    qDebug()<< addr_bc ;

    lus_tcp->sendMessage(addr_bc, ENCRYPT_YES);


}

void MainWindow::do_msg(QByteArray msg)
{

    QDomDocument xml;
    xml.setContent(msg);

    QDomElement rootnode = xml.documentElement();

    qDebug()<<msg;

    if(rootnode.tagName() == "lus_user_msg"){

        // qDebug()<<"user_msg";
        if(rootnode.attributeNode("type").value() == "mirror_msg"){

            if( rootnode.attributeNode("flag").value() == "todo_list_re"){

                QString raw_list = rootnode.attributeNode("body").value().toUtf8();

                while(ui->tableWidget->rowCount() > 0){

                    ui->tableWidget->removeRow(0);
                }

                if(raw_list.isEmpty())return;

                QByteArray by = QByteArray::fromBase64(raw_list.toLocal8Bit());

                QString list =   by;

                list = list.left(list.size()-1);
                qDebug()<<"thing "<<list;

                QStringList todo_list =  list.split("#");

                for(int i=0; i<todo_list.size(); i++){

                    qDebug()<<"list: "<<todo_list.at(i);

                    ui->tableWidget->insertRow(ui->tableWidget->rowCount());
                    ui->tableWidget->setItem(ui->tableWidget->rowCount()-1, 0, new QTableWidgetItem(todo_list.at(i)));
                }
            }
        }


        return;
    }

}


void MainWindow::todo_del(bool)
{
    int i = ui->tableWidget->rowCount()-1;

    for(; i>0 || i==0; i--){

        if(ui->tableWidget->item(i, 0)->isSelected()){

        QString cmd = "<lus_user_msg type=\"mirror_msg\" body=\"##\"  flag=\"todo_del\"/>";
        cmd.replace("##", QString::number(i));

        qDebug()<<cmd;

        lus_tcp->sendMessage(cmd.toLatin1() , ENCRYPT_YES);
        flush_todo();

        }

    }

}

void MainWindow::todo_add(bool)
{

    mirror_todo_add->exec();
    QString txt = mirror_todo_add->todo;
    if(!txt.isEmpty()){

        //QString cmd = "<lus_user_msg type=\"mirror_msg\" body=\"##\"  to_addr=\"@@\" flag=\"todo_add\"/>";
        QString cmd = "<lus_user_msg type=\"mirror_msg\" body=\"##\"  to_addr=\"\" flag=\"todo_add\"/>";

        cmd.replace("##", txt.toUtf8().toBase64());
        //cmd.replace("@@", ini_fix_id);
        //qDebug()<<cmd;
        lus_tcp->sendMessage(cmd.toLatin1() , ENCRYPT_YES);
        flush_todo();
        mirror_todo_add->todo.clear();
    }
}

void MainWindow::mirror_set(bool)
{

    mirror_set_window->exec();
    mirror_uartwrite_set();

    load_set();
    flush_mirror_faaddr();
    flush_todo();


}
void MainWindow::mirror_uartwrite_set()
{


    if(mirror_set_window->set_cmd_list.size() == 0)return;

    //获取可用串口
    const auto infos = QSerialPortInfo::availablePorts();
    for(const QSerialPortInfo &info : infos)
    {
        if(serial->isOpen())
            serial->close();

        serial->setPort(info);
        if(serial->open(QIODevice::ReadWrite))
        {

            if(info.description().indexOf("CH340") != -1){

                qDebug()<<"found ch340 " << serial->portName();

                serial->setBaudRate(115200);
                serial->setParity(QSerialPort::NoParity);
                serial->setDataBits(QSerialPort::Data8);
                serial->setStopBits(QSerialPort::OneStop);

                serial->write("<mirror_check />");
                serial->flush();
                serial->waitForReadyRead(1000);
                QString re;
                // QString re = serial.readAll();

                qDebug()<<"uart : "<<re;
                for(int i=0; i<mirror_set_window->set_cmd_list.size(); i++){


                    qDebug()<<"send "<<i<<mirror_set_window->set_cmd_list.at(i);
                    serial->write(mirror_set_window->set_cmd_list.at(i).toLatin1());
                    serial->flush();

                    mirror_set_window->set_cmd_list.removeAt(i);
                }

                return;


            }

        }


        serial->close();
    }




}


void MainWindow::mirror_about(bool)
{


    mirror_about_window->show();

}

void MainWindow::mirror_flush_man(bool)
{
    flush_mirror_faaddr();
    flush_todo();
}


void MainWindow::public_timer_fun()
{

    //qDebug()<<"timer";
  //  flush_todo();


}

void MainWindow::on_tableWidget_customContextMenuRequested(const QPoint &pos)
{


    QMenu *men = new QMenu(ui->tableWidget);

    QAction *act_add = men->addAction("添加待办");
    QAction *act_del = men->addAction("删除待办");
    QAction *act_flush = men->addAction("刷新待办");
    QAction *act_set = men->addAction("魔镜设置");
    QAction *about_set = men->addAction("联系&反馈");

    connect(act_del, SIGNAL(triggered(bool)), this, SLOT(todo_del(bool)));
    connect(act_add, SIGNAL(triggered(bool)), this, SLOT(todo_add(bool)));
    connect(act_set, SIGNAL(triggered(bool)), this, SLOT(mirror_set(bool)));
    connect(about_set, SIGNAL(triggered(bool)), this, SLOT(mirror_about(bool)));
    connect(act_flush, SIGNAL(triggered(bool)), this, SLOT(mirror_flush_man(bool)));

    men->exec(QCursor::pos());

}

void MainWindow::load_set(void)
{


    QSettings set("mirror_set.ini", QSettings::IniFormat);
    ini_fix_id = set.value("main/fix_id").toString();
    qDebug()<<"mirror fix_id" << ini_fix_id;
    lus_tcp->lus_set_dst(ini_fix_id);
}

void MainWindow::closeEvent(QCloseEvent *event)
{
    event->ignore();
    this->hide();
    if(mSysTrayIcon == NULL){


        mSysTrayIcon = new QSystemTrayIcon(this);//新建QSystemTrayIcon对象
        QIcon icon = QIcon(":/log_l.ico");//新建托盘要显示的icon
        mSysTrayIcon->setIcon(icon);//将icon设到QSystemTrayIcon对象中
        mSysTrayIcon->setToolTip(QString::fromLocal8Bit("魔镜，魔镜..."));//当鼠标移动到托盘上的图标时，会显示此处设置的内容

        connect(mSysTrayIcon,SIGNAL(activated(QSystemTrayIcon::ActivationReason)),
                this,SLOT(on_activatedSysTrayIcon(QSystemTrayIcon::ActivationReason)));//给QSystemTrayIcon添加槽函数


        createActions();//建立托盘操作的菜单
        createMenu();

        mSysTrayIcon->show();//在系统托盘显示此对象


    }

}

void MainWindow::on_activatedSysTrayIcon(QSystemTrayIcon::ActivationReason reason)
{
    switch(reason){
    case QSystemTrayIcon::Trigger://单击鼠标左键
        break;
    case QSystemTrayIcon::DoubleClick:
        this->show();
        break;
    default:
        break;
    }
}
void MainWindow::createActions()
{
    mShowMainAction = new QAction(QString::fromLocal8Bit("显示主界面"),this);
    connect(mShowMainAction,SIGNAL(triggered()),this,SLOT(on_showMainAction()));

    mExitAppAction = new QAction(QString::fromLocal8Bit("退出"),this);
    connect(mExitAppAction,SIGNAL(triggered()),this,SLOT(on_exitAppAction()));

}
void MainWindow::createMenu()
{
    mMenu = new QMenu(this);
    mMenu->addAction(mShowMainAction);

    mMenu->addSeparator();

    mMenu->addAction(mExitAppAction);

    mSysTrayIcon->setContextMenu(mMenu);
}

void MainWindow::on_showMainAction()
{
    this->show();
    mSysTrayIcon->hide();
}

void MainWindow::on_exitAppAction()
{
    delete mSysTrayIcon;
    exit(0);
}

